import axios from "axios"; // 引入axios插件
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { serverUrl, getToken } from "./tools";

const instance = axios.create({
  baseURL: serverUrl, // 请求的基础地址，会拼接在每一个请求之前
  timeout: 5000,
});

// axios请求拦截器
// Add a request interceptor
// 全局请求拦截，网络请求发起之前执行
instance.interceptors.request.use(
  function(config) {
    // Do something before request is sent
    NProgress.start(); // 显示进度条
    config.headers.token = getToken(); // 此处的token属性是服务器端给的名字，你以后上班了要根据你们公司服务器端给的名字改一下
    return config;
  },
  function(error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
// 全局响应拦截，网络请求结束之后执行
instance.interceptors.response.use(
  function(response) {
    NProgress.done(); // 隐藏进度条
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    // axios返回的数据在data属性中
    return response.data;
  },
  function(error) {
    // console.dir(error);
    if (error.response?.status === 401) {
      // 401需要跳转到登录页
      window.location.href = "/#/login";
    }
    NProgress.done();
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  }
);

/**
 * get请求
 * @param {*} url     地址
 * @param {*} params  参数
 * @returns
 */
export const get = (url, params) => instance.get(url, { params });

/**
 * post
 * @param {*} url   地址
 * @param {*} data  数据
 * @returns
 */
export const post = (url, data) => instance.post(url, data);

/**
 * put
 * @param {*} url   地址
 * @param {*} data  数据
 * @returns
 */
export const put = (url, data) => instance.put(url, data);

/**
 * delete
 * @param {*} url   地址
 * @returns
 */
export const del = (url) => instance.delete(url);
